import { PlayerGroup } from "@sapi-game/gamePlayer";
import { DirtShopContext } from "./context";
import { DirtShopConfig } from "./interface";
import { DirtShopMoudle } from "./module";
import { DirtShopLoadState } from "./states/loadState";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { GameMode, world } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { AutoStopState } from "@sapi-game/gameState/common/autoStop";

export class DirtShopGame extends DirtShopMoudle.Engine<{
    host: PlayerGroup;
    attacker: PlayerGroup;
    config: DirtShopConfig;
}> {
    protected override buildContext(config: {
        host: PlayerGroup;
        attacker: PlayerGroup;
        config: DirtShopConfig;
    }): DirtShopContext {
        const host = this.groupBuilder.fromGroup(config.host);
        const attacker = this.groupBuilder.fromGroup(config.attacker);
        return new DirtShopContext(host, attacker, config.config);
    }

    override onStart(): void {
        this.pushState(AutoStopState, {
            groupSet: this.context.groupSet,
        }).pushState(DirtShopLoadState);
    }

    override onStop(): void {
        this.killEntity();
        this.context.groupSet.forEach((p) => {
            p.player.setGameMode(GameMode.Adventure);
            p.player.setSpawnPoint();
            p.runCommand("effect @s clear");
            p.clear();
            p.player.teleport(
                { x: 1917, y: -60, z: 1906 },
                { dimension: Dimensions.Overworld }
            );
        });
        world.gameRules.pvp = false;
    }

    killEntity() {
        this.context.map.region
            .getEntitesInRegion({ excludeTypes: [EntityTypeIds.Player] })
            .forEach((e) => e.remove());
    }
}
